package com.ece;

import javax.persistence.EntityManager;

import com.ece.beans.Commande;
import com.ece.beans.items.DVD;
import com.ece.beans.items.Livre;
import com.ece.beans.users.Utilisateur;
import com.ece.persistence.PersistenceUtil;
import com.ece.users.UtilisateurBusinessController;

public class KiwiMainBusiness {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DVD dvd = new DVD("DVD 1", 9.99f, "La Fureur du Dragon", 2);
		Livre livre = new Livre("Livre 2", 6f, "God Hates Us All", "Hank Moody");

		// Start JPA/Hibernate and load persistence.xml config
		PersistenceUtil.init();
		// First work unit
		EntityManager em = PersistenceUtil.getEM();
		try {
			PersistenceUtil.beginTransaction();
			em.persist(dvd);
			em.persist(livre);
			PersistenceUtil.commitTransaction();
		}
		finally { PersistenceUtil.closeEM(); }
		System.out.println(dvd.getLibelle());
		System.out.println(livre.getLibelle());

		DVD dvdBis = new DVD();
		Livre livreBis = new Livre();
		em = PersistenceUtil.getEM();
		try {
			PersistenceUtil.beginTransaction();
			dvdBis = em.find(DVD.class, "DVD 2");
			livreBis = em.find(Livre.class, "Livre 1");
			PersistenceUtil.commitTransaction();
		}
		finally { PersistenceUtil.closeEM(); }
		if(dvdBis != null)
			System.out.println(dvdBis.getLibelle() + "\n" + dvdBis.getZone());
		else
			System.out.println("Pas de DVD");
		if(livreBis != null)
			System.out.println(livreBis.getLibelle() + "\n" + livreBis.getAuteur());
		else
			System.out.println("Pas de livre");


		Utilisateur user;
		user = new UtilisateurBusinessController().login("laurisbraka@gmail.com", "pass");
		em = PersistenceUtil.getEM();
		try {
			PersistenceUtil.beginTransaction();
			user = em.find(Utilisateur.class, "laurisbraka@gmail.com");
			PersistenceUtil.commitTransaction();
		}
		finally { PersistenceUtil.closeEM(); }
		if(user == null)
			System.out.println("User non existant");
		else if(!"pass".equals(user.getPass()))
			System.out.println("Mauvais mdp");
		else
			System.out.println("Bonjour " + user.getPrenom() + " " + user.getNom());

		Commande commande = new Commande(user);
		commande.addItem(livre);
		commande.addItem(dvd);
		try {
			commande.validerCommande();
			System.out.println(commande.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
